<template>
  <!-- 招聘变化趋势 -->
  <div class="wrapper">
    <div class="chartMain">
      <template v-if="chartDataIsNotEmpty">
        <div class="h100" ref="line_echartDom"></div>
        <div class="regionLineDesc">
          <div
            class="regionLineDescItem"
            v-for="(item, index) in chartData.city"
            :key="index"
          >
            <div class="descTitle">{{ item.name }}招聘热度平均约为</div>
            <div class="descNum">
              {{ averageCitySalary(item.salary) }}
            </div>
            <div class="descNumTips">
              注释:热度值主要通过大数据分析模型得出一个具体的数值,主要跟职位招聘数量、职位招聘薪资等数据相关,数据在0-100之间,数据越高代表该职位市场需求量越大,数据仅供参考.
            </div>
          </div>
        </div>
      </template>
      <el-empty class="empty" description="暂无数据" v-else
        ><el-button type="primary" size="mini" @click="handleKnowClick()">
          想要了解
        </el-button></el-empty
      >
    </div>
  </div>
</template>

<script>
import { getRecruitheat, reportLackDataPosition } from '@/api/salary';
export default {
  name: 'recruitHeatLineChart',
  components: {},
  data() {
    return {
      chartData: {},
      chartDataIsNotEmpty: true, //必须让图表先显示，不然会出现空白
      average: '',
      isSetDeaultTime: false,
      isSetDeaultRegion: true,
      isLabelShow: false
    };
  },
  created() {
    this.isLabelShow = this.$route.query.isLabelShow;
  },
  mounted() {
    this.fetchData();
  },
  methods: {
    fetchData() {
      this.listLoading = true;
      const params = {
        id: this.$route.query.id
      };
      params.regionIds = '100000';
      getRecruitheat(params)
        .then((response) => {
          if (response.code == 200) {
            this.chartData = this.handleData(response.data);
            this.chartDataIsNotEmpty =
              response.data && response.data.length > 0;
            setTimeout(() => {
              this.init();
            }, 500);
          } else {
            this.chartDataIsNotEmpty = false;
          }
        })
        .catch(() => {
          this.chartDataIsNotEmpty = false;
        });
    },
    handleData(data) {
      let dataArr = {
        city: [],
        time: [],
        name: []
      };
      if (data[data.length - 1]) {
        data[data.length - 1].list.forEach((item) => {
          dataArr.time.push(`${item.month}${item.year}`);
        });
      }
      dataArr.city = data.map((item) => {
        if (item) {
          dataArr.name.push(item.regionName);
          const salary = [];
          item.list.forEach((item) => {
            salary.push(item.heatNum);
          });
          return { name: item.regionName, salary };
        }
      });
      return dataArr;
    },
    init() {
      if (!this.$refs['line_echartDom']) return;
      this.myChart = this.$echarts.init(this.$refs['line_echartDom']);
      let city = this.chartData.city,
        name = this.chartData.name,
        time = this.chartData.time;
      let option = {
        color: [
          '#F359AE',
          '#34CA6F',
          '#066BFF',
          '#75E0FF',
          '#FFA506',
          '#3ba272',
          '#fc8452',
          '#9a60b4',
          '#ea7ccc'
        ],
        xAxis: {
          type: 'category',
          data: time,
          name: '(月份)',
          // boundaryGap: false,
          axisLabel: {
            formatter(val) {
              // 当字符串长度超过2时
              if (val.length > 2) {
                // 把字符串分割成字符串数组
                const array = val.split('');
                const index = array.indexOf('月');
                //在下标2处删除0个，加上回车
                array.splice(index + 1, 0, '\n\n');
                return array.join('');
              } else {
                return val;
              }
            },
            color: '#8193B2',
            fontSize: '12px'
          },
          axisLine: {
            lineStyle: {
              color: '#E4EDF8'
            }
          },
          nameTextStyle: {
            lineHeight: 80, //标题行高
            color: '#8193B2',
            verticalAlign: 'top', //标题位置
            fontSize: '12px', // 设置最大宽度
            padding: [-28, 0, 0, 0] // 上右下左与原位置距离
          }
        },
        tooltip: {
          trigger: 'axis'
        },
        // legend: {
        //   data: name,
        //   orient: "horizontal",
        //   align: "left",
        //   colorBy: "",
        //   x: "left", //可设定图例在左、右、居中
        //   y: "top", //可设定图例在上、下、居中
        //   icon: "circle",
        //   itemGap: 36,
        //   itemWidth: 8,
        //   itemHeight: 10,
        //   textStyle: {
        //     fontSize: "14px",
        //   },
        //   padding: [20, 0, 20, 0],
        // },
        grid: {
          right: '50',
          bottom: '30',
          top: '40', //"100"
          left: '8',
          containLabel: true
        },
        yAxis: {
          type: 'value',
          min: 20,
          max: 100,
          //   splitNumber: 5,
          // minInterval: 1,
          scale: true,
          name: '（热度值）',
          axisLabel: {
            color: '#8193B2',
            fontSize: '12px'
          },
          nameTextStyle: {
            padding: [20, 40, 10, 25], // 上右下左与原位置距离
            color: '#8193B2'
          }
        },
        series: []
      };
      option.series = [];
      this.myChart.clear();
      city.forEach((item) => {
        option.series.push({
          data: item.salary,
          name: item.name,
          type: 'line',
          smooth: true,
          symbolSize: 10,
          symbol: 'path://M349 889.5a7.5 7.5 0 1 0 15 0a7.5 7.5 0 1 0 -15 0z',
          // showSymbol: false,
          label: {
            normal: {
              show: true
            }
          },
          emphasis: {
            label: {
              // show: true,
            }
          }
        });
      });
      option && this.myChart.setOption(option);
      window.addEventListener('resize', () => {
        if (this.myChart) {
          this.myChart.resize();
        }
      });
      if (!this.isLabelShow) {
        this.myChart.dispatchAction({
          type: 'showTip',
          seriesIndex: 0,
          dataIndex: 1
        });
      }
    },
    averageCitySalary(values) {
      let salary = 0;
      values.forEach((item, index) => {
        salary = salary + item;
      });

      if (values.length > 0) {
        const result = salary / values.length;
        return result.toFixed(1);
      } else {
        return '保密';
      }
    },
    handleKnowClick() {
      const userInfo = JSON.parse(localStorage.getItem('userInfo')); //OA的userInfo和SaaS登录的userInfo不一样
      const oaId = '';
      if (userInfo && userInfo.user_source_id) {
        oaId = userInfo.user_source_id;
      }
      const params = {
        positionId: this.$route.query.id,
        positionName: this.$route.query.name,
        layerId: '122',
        layerName: '招聘变化趋势',
        personId: localStorage.getItem('personId') || '',
        oaId: oaId
      };
      reportLackDataPosition(params).then((response) => {
        if (response.code == 200) {
          this.$message.success('已成功提交');
        } else {
          this.$message.error(res.status_desc);
        }
      });
    }
  }
};
</script>

<style lang="scss" scoped>
.wrapper {
  width: 100%;
}

.chartMain {
  display: flex;
  align-items: center;
  padding-bottom: 15px;
  .empty {
    margin: auto;
    ::v-deep .el-empty__image {
      width: 150px;
    }
  }
}
.regionLineChart {
  display: flex;
  align-items: center;
}
.regionLineDesc {
  display: flex;
  flex: 0.3;
  flex-wrap: wrap;
  // width: 400px;
  justify-content: left;
  align-content: center;
  margin: 10px;
}

.regionLineDescItem {
  margin: 10px 0px;
  width: 80%;
}
.descTitle {
  color: #555;
  font-size: 15px;
}
.descNum {
  display: flex;
  align-items: baseline;
  color: #1b78ff;
  font-size: 24px;
  font-weight: bold;
  margin-top: 22px;
  font-family: D-DIN-PRO-500-Medium;
}
.descNumTips {
  margin: 10px 0px;
  color: #888;
  font-size: 15px;
}
.rmb {
  font-size: 18px;
}
.h100 {
  flex: 0.7;
  height: 20vw;
  width: 100%;

  min-width: 615px;
  min-height: 240px;
}
</style>
